var memberServiceNative = require("../services/memberService.js");
var storeServiceNative = require('../services/storeService');
var merchantServiceNative = require('../services/MerchantService');
var errorHandler = require('../common/errorHandler');
var idHelper = require("../common/utils/id-helper");
var async = require("async");
var moment = require("moment");
var httpreq = require("httpreq");

var MemberRegisterController = {
	sendSms: function (req, res, next) {
		var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);
		var merchantService = errorHandler.errorToResponse(req, res, merchantServiceNative);
		var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);
		var mobile = req.body.account;
		var storeId = req.params.storeId;
		if (!idHelper.isMobile(mobile)) {
			return res.send({error: {message: '手机号无法识别', code: "is_not_mobile"}});
		}
		memberService.getMemberByAccount(storeId, mobile, function (err, data) {
			if (err) {
				return res.status(400).json({error: '参数错误'});
			}
			if (data) {
				return res.status(400).json({error: '您已经是本店会员，不用再注册'});
			}
			var code = '';
			var newVerficationCodeTime = new Date().getTime();

			if (!req.session['registerCodeInfo']) {
				code = idHelper.verficationCode();
			} else {
				var time = req.session['registerCodeInfo'].startTime + 5 * 60 * 1000;
				if (time < newVerficationCodeTime) {
					code = idHelper.verficationCode();
				} else {
					newVerficationCodeTime = req.session['registerCodeInfo'].startTime;
					code = req.session['registerCodeInfo'].code;
				}
				if (req.session['registerCodeInfo'].mobile != mobile) {
					code = idHelper.verficationCode();
				}
			}
			var merchant = {};
			var merchantId = '';
			async.series([
				function (cb) {
					storeService.getStoreById(storeId, null, function (err, store) {
						if (err) {
							return res.status(400).json({error: "参数错误"});
						}
						merchantId = store.merchant_id;
						cb(err, store);
					})
				},
				function (cb) {
					merchantService.getMerchantById(merchantId, function (err, merchantData) {
						if (err) {
							return res.status(400).json({error: "参数错误"});
						}
						merchant = merchantData;
						cb(err, merchantData)
					})
				}
			], function (err, result) {
				var msg = "验证码：" + code + "，您正在注册店铺" + result[1].name + "的会员，请使用收到的验证进行会员注册。【门铺集】";
				if (process.env.NODE_ENV == 'test') {
					req.session['registerCodeInfo'] = {code: code, mobile: mobile, startTime: newVerficationCodeTime};

					console.log(msg);
					return res.send({message: "验证码发送成功"});
				} else {
					storeService.sendSMSToMember(code, mobile, merchant, function (err, data) {
						console.log('send msg ok');
						req.session['registerCodeInfo'] = {code: code, mobile: mobile, startTime: newVerficationCodeTime};
						return res.send({message: "验证码发送成功"});
					}, msg)
				}
			})
		});
	},
	register: function (req, res, next) {
		try {
			var storeId = req.params.storeId;
			var member = req.body;
			if (!req.session['registerCodeInfo']) {
				return res.status(400).json({error: '已超时请重新获取注册验证码！'});
			}
			var time = req.session['registerCodeInfo'].startTime + 5 * 60 * 1000;
			var newVerficationCodeTime = new Date().getTime();
			if (time < newVerficationCodeTime) {
				return res.status(400).json({error: '已超时请重新获取注册验证码！'});
			}
			if (req.session['registerCodeInfo'].code != member.autoCode) {
				return res.status(400).json({error: '动态登录密码错误'});
			}
			if (req.session['registerCodeInfo'].mobile != member.mobile) {
				return res.status(400).json({error: '请填写正确的手机号'});
			}

			var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);
			var merchantService = errorHandler.errorToResponse(req, res, merchantServiceNative);
			var memberService = errorHandler.errorToResponse(req, res, memberServiceNative);
			member.id = idHelper.createId();


			//idvarchar(255) NOT NULL
			member.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
			member.joinDate = member.createTime;
			member.memberNumber = member.mobile;
			var merchantId = '';
			async.series(
				[
					function (cb) {
						storeService.getStoreById(storeId, '', function (err, store) {
							if (err) {
								return res.status(500).send(err);
							}
							if (!store) {
								return res.status(500).send(err);
							}
							merchantId = store.merchant_id || store.MERCHANT_ID;
							cb(err, store);
						});
					},
					function (cb) {
						merchantService.getMerchantById(merchantId, function (err, data) {
							if (err) {
								return res.status(500).send(err);
							}
							cb(err, data);
						});
					}
				],
				function (err, result) {
					member.merchant_id = merchantId;
					member.mgmtDomain = storeId;
					var url = '';
					var s = encodeURI(member.name);
					if (process.env.NODE_ENV == 'test') {
						url = 'http://localhost:9090/api/util/searchCode?text=' + s;
					}
					else
						url = 'http://javaserver.local/api/util/searchCode?text=' + s;
					httpreq.get(url, function (err, data) {
						if (err) {
							console.log("get searchCode:" + err.toString() + ' object:' + err);
							return res.status(500).send(err);
						}
						var parse = JSON.parse(data.body);
						member.searchCode = parse.code;
						memberService.saveMember(member, function (err, data) {
							if (err) return res.status(500).send(err);
							return res.send(member);
						})

					});
				}
			);
		} catch (err) {
			console.log("register member error msg:" + err.toSource() + " object:" + err);
			return res.status(500).send(err);
		}
	}
};


module.exports = MemberRegisterController;